<template>
  <div class="app-container">
    <Modal
        v-model="modal"
        title="设备绑定会议室"
        :closable="false"
        :mask-closable="false"
        :z-index="900">
        <Input v-model="room" placeholder="请输入会议室编号" style="width: 60%;" />
        <div slot="footer">
            <Button type="primary" @click="bindRoom">确认</Button>
        </div>
    </Modal>
    <Modal
        v-model="modal1"
        title="请确认"
        @on-ok="handleConfirm">
        <p>您输入的会议室编号为{{ room }}</p>
    </Modal>
    <Row type="flex" justify="center" align="middle">
      <!-- <Col :xs="6" :sm="6" :md="6" :lg="6"></Col> -->
      <Col :xs="8" :sm="8" :md="8" :lg="8">
        <h1 style="font-size:3rem;font-family:'KaiTi';margin-top:.5rem">会议室：<span>{{ room }}</span></h1>
      </Col>
      <!-- <Col :xs="6" :sm="6" :md="6" :lg="6"> -->
        <!-- <h1 style="font-size:1.2rem;font-family:'KaiTi';">{{ current }}</h1> -->
      <!-- </Col> -->
    </Row>
    <div class="meeting-card">
      <Row type="flex" justify="center" class="meeting-status">
        <Col :xs="20" :sm="20" :md="20" :lg="20">
        <Tabs value="1">
          <TabPane label="当前会议情况" name="1">
            <div class="left">
              <Row type="flex" justify="center" align="middle" style="padding-top:.5rem" class="rows">
                <Col :xs="12" :sm="8" :md="12" :lg="12">
                <h1>会议主题：</h1>
                </Col>
                <Col :xs="6" :sm="6" :md="6" :lg="6">
                <div class="theme">{{ now.theme }}</div>
                </Col>
              </Row>
              <Row type="flex" justify="center" align="middle" style="padding-top:.5rem" class="rows">
                <Col :xs="12" :sm="8" :md="12" :lg="12">
                <h1>开始时间：</h1>
                </Col>
                <Col :xs="6" :sm="6" :md="6" :lg="6">
                <div class="time">{{ (now.stime) }}</div>
                </Col>
              </Row>
              <Row type="flex" justify="center" align="middle" style="" class="rows">
                <Col :xs="12" :sm="12" :md="12" :lg="12">
                <h1>结束时间：</h1>
                </Col>
                <Col :xs="6" :sm="6" :md="6" :lg="6">
                <div class="time">{{ (now.etime) }}</div>
                </Col>
              </Row>
              <Row type="flex" justify="center" style="" class="rows">
                <Col :xs="12" :sm="12" :md="12" :lg="12">
                <h1>会议状态：</h1>
                </Col>
                <Col :xs="6" :sm="6" :md="6" :lg="6" style="margin-bottom:1rem">
                <i-circle :percent="percent" :stroke-width="8" :trail-width="7" stroke-color="#3f67cc" trail-color="#bdbdbd" style="width:80%;height:80%;margin-bottom:1.5rem">
                  <p style="padding-top:1rem;font-size:1.5rem;color:#4169cc;font-weight:bold">{{ status }}</p>
                  <p v-show="isMeeting" style="font-size:1.5rem;margin-top:.5rem;color:#4169cc;font-weight:bold">{{ `${percent}%` || '当前无会议' }}</p>
                </i-circle>
                </Col>
              </Row>
            </div>

            <div class="right">
              <Row type="flex" justify="center" align="middle" class="btnContainer">
                <Col :xs="12" :sm="16" :md="24" :lg="24" class="btnCol">
                  <Button id="button" size="large" type="primary" @click="turnOn" style="margin: 1rem 1rem 1rem 0;">开启摄像头</Button>
                  <Button id="button" size="large" type="primary" @click="turnOff" style="margin: 1rem 0 1rem 1rem;">关闭摄像头</Button>
                </Col>
              </Row>
              <Row type="flex" justify="center" align="middle" class="videoContainer">
                <Col :xs="12" :sm="12" :md="24" :lg="24" class="videoCol">
                  <video id="video" />
                  <div style="margin: 0 auto;width:300px;height:300px;position: relative;">
                    <canvas v-show="isShow" id="canvas" />
                    <canvas v-show="!isShow" id="canvas1" />
                    <Spin size="large" fix v-if="spinShow"></Spin>
                  </div>
                </Col>
              </Row>
              <Row type="flex" justify="center" align="middle" class="btnContainer">
                <Col :xs="12" :sm="12" :md="12" :lg="12" class="btnCol">
                  <Button long id="snap" size="large" type="primary" style="letter-spacing: 1rem;" @click="photo">点击拍<span style="letter-spacing: 0;">照</span></Button>
                </Col>
              </Row>
            </div>
          </TabPane>
          <TabPane label="当天使用情况" name="2">
            <div class="left2">
              <Row type="flex" style="margin-left:1rem;height:90%">
                <Col :xs="12" :sm="18" :md="24" :lg="24">
                <Table border disabled-hover size="large" class="table" :row-class-name="rowClassName"
                  :columns="columns1" :data="today">
                </Table>
                </Col>
              </Row>
            </div>
            <div class="right2">
              <Row type="flex" justify="center" align="middle">
                <Col :xs="12" :sm="12" :md="20" :lg="20">
                  <img style="width:80%;height:80%" :src="imgSrc" alt="二维码">
                  <p style="padding-top:2rem;color:#000;font-size:2.2rem;font-weight:bold">扫码预定该会议室</p>
                </Col>
              </Row>
            </div>
          </TabPane>
        </Tabs>
        </Col>
      </Row>
    </div>
      <h1 style="font-size:1.2rem;position: absolute;right: 1rem;bottom: 0;">{{ current }}</h1>
  </div>
</template>

<script>
import $ from 'jquery'
import 'jquery.ripples'
import { faceCompare } from '@/api/face.js'
import { AllDayMeetingInfo } from '@/api/front'
import QRCode from 'qrcode'
import { takePhoto } from '@/utils/camera.js'
import { parseTime } from '@/utils/index.js'
import { getRoomId, setRoomId } from '@/utils/bind.js';

export default {
  filters: {
    parseTime(time) {
      const date = new Date(time)
      return parseTime(date, '{h}:{i}')
    }
  },
  data() {
    return {
      modal: false,
      modal1: false,
      room: getRoomId(),
      status: '',
      isShow: false,
      spinShow: false,
      isMeeting: false,
      percent: 0,
      now: {},
      today: [],
      options: {
        margin: 0,
        height: 200,
        width: 200
      },
      videoHeight: '',
      videoWidth: '',
      imgSrc: '',
      columns: [],
      data: [],
      columns1: [{
        title: '时间',
        key: 'time',
        align: 'center',
        width: 190
      },
      {
        title: '会议主题',
        key: 'theme',
        align: 'center'
      },
      {
        title: '预订人',
        key: 'sponsor',
        align: 'center'
      },
      {
        title: '状态',
        key: 'status',
        align: 'center'
      }
      ],
      streaming: false,
      stream: null,
      current: ''
    }
  },
  created() {
    this.modal = this.room ? false : true
    if (!this.modal) {
      this.getList()
      setInterval(() => {
        this.getList()
      }, 300000)
      
      this.getCurrent()
      setInterval(() => {
        this.getCurrent()
      }, 6000)

      setInterval(() => {
        this.getTime()
      }, 1000)
    }
  },
  mounted() {
    /* $('.app-container').ripples({
      resolution: 512,
      dropRadius: 20 // px
    }) */
    if (!this.modal) {
      QRCode.toDataURL(this.room, this.options).then(url => {
        // console.log(url)
        this.imgSrc = url
      }).catch(err => {
        console.log(err)
      })
    }
  },
  methods: {
    getTime() {
      this.current =  parseTime(new Date().getTime(), '{m}/{d} {h}:{i}:{s}')
    },
    bindRoom() {
      this.modal1 = true
    },
    handleConfirm() {
      this.modal = false
      setRoomId(this.room)
      let NewPage = '_empty' + '?time=' + new Date().getTime()/500
      this.$router.push(NewPage)
      this.$router.go(-1)
    },
    async getList() {
      const todayuse = await AllDayMeetingInfo(this.room)
      this.today = todayuse.data.data
      this.today.forEach(data => {
        this.transformState(data)
        data.time = `${parseTime(data.starttime, '{h}:{i}')} - ${parseTime(data.endtime, '{h}:{i}')}`
      })
      while (this.today.length < 7) {
        this.today.push({ time: '', theme: '', originatorName: '', state: '' })
      }
    },
    getCurrent() {
      const currentTime = new Date().getTime() / 1000
      // console.log(parseTime(new Date().getTime()))
      this.now = {}
      let count = 0
      let indexs = []
      this.today.forEach((data, index) => {
        if (data.starttime - 30 * 60 < currentTime && data.endtime > currentTime) {
          count++
          indexs.push(index)
        }
      })
      switch (count) {
        case 0:
          this.now.theme = '无'
          this.now.stime = '-'
          this.now.etime = '-'
          this.isMeeting = false
          this.percent = 0
          this.status = '未进行'
          break
        case 1:
          this.isMeeting = false
          this.percent = 0
          this.status = '未进行'
          this.now = this.today[indexs[0]]
          this.now.stime = parseTime(this.now.starttime, '{h}:{i}')
          this.now.etime = parseTime(this.now.endtime, '{h}:{i}')
          if (currentTime >= this.today[indexs[0]].starttime) {
            this.calculatePercent()
          }
          break
        case 2:
          if (currentTime <= this.today[indexs[0]].endtime) {
            this.now = this.today[indexs[0]]
            this.now.stime = parseTime(this.now.starttime, '{h}:{i}')
            this.now.etime = parseTime(this.now.endtime, '{h}:{i}')
            this.calculatePercent()
          } else {
            this.now = this.today[indexs[1]]
            this.now.stime = parseTime(this.now.starttime, '{h}:{i}')
            this.now.etime = parseTime(this.now.endtime, '{h}:{i}')
            this.calculatePercent()
          }
          break
        default:
          break
      }
    },
    /* eslint-disable */
      turnOn() {
        this.spinShow = true
        setTimeout(() => {
          this.isShow = true
        }, 700)
        let _this = this
        let videoWidth, videoHeight;

      // whether streaming video from the camera.
        let video = document.getElementById('video');
        let canvasOutput = document.getElementById('canvas');
        let canvasOutputCtx = canvasOutput.getContext('2d');
        let faceClassifier = null;
        let eyeClassifier = null;

        let src = null;
        let dstC1 = null;
        let dstC3 = null;
        let dstC4 = null;

        let canvasInput = null;
        let canvasInputCtx = null;

        let canvasBuffer = null;
        let canvasBufferCtx = null;
        var srcMat=new Object();
        var grayMat=new Object();
        function startCamera() {
            if (_this.streaming) return;
            navigator.mediaDevices.getUserMedia({video: true, audio: false})
                .then(function(s) {
                    _this.stream = s;
                    video.srcObject = s;
                    video.play();
                })
                .catch(function(err) {
                    console.log("An error occured! " + err);
                });

            video.addEventListener("canplay", function(ev){
                if (!_this.streaming) {
                    videoWidth = video.videoWidth;
                    videoHeight = video.videoHeight;
                    video.setAttribute("width", videoWidth);
                    video.setAttribute("height", videoHeight);
                    canvasOutput.width = videoWidth;
                    canvasOutput.height = videoHeight;
                    _this.streaming = true;
                }
                startVideoProcessing();
            }, false);
        }
        function startVideoProcessing() {
            if (!_this.streaming) { console.warn("Please startup your webcam"); return; }
            stopVideoProcessing();
            canvasInput = document.createElement('canvas');
            canvasInput.width = videoWidth;
            canvasInput.height = videoHeight;
            canvasInputCtx = canvasInput.getContext('2d');

            canvasBuffer = document.createElement('canvas');
            canvasBuffer.width = videoWidth;
            canvasBuffer.height = videoHeight;
            canvasBufferCtx = canvasBuffer.getContext('2d');

            srcMat = new cv.Mat(videoHeight, videoWidth, cv.CV_8UC4);
            grayMat = new cv.Mat(videoHeight, videoWidth, cv.CV_8UC1);

            faceClassifier = new cv.CascadeClassifier();
            faceClassifier.load('haarcascade_frontalface_default.xml');


            requestAnimationFrame(processVideo);
        }

        function processVideo() {
            // stats.begin();
            canvasInputCtx.drawImage(video, 0, 0, videoWidth, videoHeight);
            let imageData = canvasInputCtx.getImageData(0, 0, videoWidth, videoHeight);
            srcMat.data.set(imageData.data);
            cv.cvtColor(srcMat, grayMat, cv.COLOR_RGBA2GRAY);
            let faces = [];
            let size;

            let faceVect = new cv.RectVector();
            let faceMat = new cv.Mat();
            cv.pyrDown(grayMat, faceMat);
            size = faceMat.size();

            cv.pyrDown(grayMat, faceMat);
            cv.pyrDown(faceMat, faceMat);
            size = faceMat.size();

            faceClassifier.detectMultiScale(faceMat, faceVect);
            for (let i = 0; i < faceVect.size(); i++) {
                let face = faceVect.get(i);
                if (i>=2) {
                    var face2 = faceVect.get(i - 1);
                    var face3 = faceVect.get(i - 2);
                    try {
                      faces.push(new cv.Rect((face.x * 0.4 + face2.x * 0.35 + face3.x * 0.25), (face.y * 0.4 + face2.y * 0.35 + face3.y * 0.25), (face.width * 0.4 + face2.width * 0.35 + width.height * 0.25), (face.height * 0.4 + face2.height * 0.35 + face3.height * 0.25  )))
                    } catch (ReferenceError) {
                      continue
                    }
                }
                else {
                    faces.push(new cv.Rect(face.x, face.y, face.width, face.height));
                }
            }
            faceMat.delete();
            faceVect.delete();

            canvasOutputCtx.drawImage(canvasInput, 0, 0, videoWidth, videoHeight);
            drawResults(canvasOutputCtx, faces, 'red', size);

            requestAnimationFrame(processVideo);
        }

        function drawResults(ctx, results, color, size) {
            for (let i = 0; i < results.length; ++i) {
                let rect = results[i];
                let xRatio = videoWidth/size.width;
                let yRatio = videoHeight/size.height;
                ctx.lineWidth = 3;
                ctx.strokeStyle = color;
                ctx.strokeRect(rect.x*xRatio, rect.y*yRatio, rect.width*xRatio, rect.height*yRatio);
            }
        }

        function stopVideoProcessing() {
            if (src != null && !src.isDeleted()) src.delete();
            if (dstC1 != null && !dstC1.isDeleted()) dstC1.delete();
            if (dstC3 != null && !dstC3.isDeleted()) dstC3.delete();
            if (dstC4 != null && !dstC4.isDeleted()) dstC4.delete();
        }

        function initUI() {
            // stats = new Stats();
            // stats.showPanel(0);
            document.getElementById('container').appendChild(stats.dom);
        }

        function opencvIsReady() {
            console.log('OpenCV.js is ready');
            // let canvas = document.getElementById("canvas")
            // canvas.setAttribute('style', 'display:inline-block')
            // initUI();
            startCamera();
            setTimeout(() => {
              _this.spinShow = false
            }, 700)
        }
        opencvIsReady();
      },
      turnOff() {
        let _this = this
        let video = document.getElementById('video');

        function stopCamera() {
          if (!_this.streaming) return;
          let canvas = document.getElementById("canvas")
          canvas.setAttribute('style', 'display:none')
          video.pause();
          video.srcObject=null;
          _this.stream.getVideoTracks()[0].stop();
          _this.streaming = false;
        }
        stopCamera()
        this.isShow = false
      },
      getVideoSize() {
        const video = document.getElementById('video')
        this.videoHeight = video.height
        this.videoWidth = video.width
      },
      photo() {
        const video = document.getElementById('video')
        const canvas = document.getElementById('canvas')
        this.getVideoSize()
        let type = 'jpeg'
        let quality = 1
        // let width = this.videoWidth
        // let height = this.videoHeight
        // console.log(`height:`, this.videoHeight)
        // console.log(`width:`, this.videoWidth)
        const base64 = []
        for (let index = 0; index < 5; index++) {
          base64.push(takePhoto(type,quality,video,canvas,this.videoWidth,this.videoHeight))
          this.sleep(200)
          // console.log(takePhoto(type,quality,video,canvas,width,height))
        }
        faceCompare({
          meeting: this.now.id,
          img1:base64[0].base64,
          img2:base64[1].base64,
          img3:base64[2].base64,
          img4:base64[3].base64,
          img5:base64[4].base64}).then(res => {
          if (!res.data.code) {
            this.$Notice.success({
              title: `识别成功,欢迎您  ${res.data.data.name}~`,
              duration: 2
            })
            // eslint-disable-next-line no-undef
            powerOn()
          } else {
            this.$Notice.error({
              title: res.data.msg,
              duration: 2
            })
          }
        })
      },
      //实现表格斑马纹效果
      rowClassName(row, index) {
        if (index % 2 === 0) {
          return 'ivu-table-stripe-even';
        } else return 'ivu-table-stripe-odd';
      },
      sleep(delay) {
        let start = (new Date()).getTime()
        while((new Date()).getTime() - start < delay){
          continue;
        }
      },
      //计算会议进度
			calculatePercent() {
        this.isMeeting = true
        const time = this.now.endtime - this.now.starttime
        const currentTime = new Date().getTime() / 1000
        const meetingTime = currentTime - this.now.starttime
        // console.log(time)
        // console.log(meetingTime)
        this.percent = Math.floor(meetingTime / time * 100)
        this.status = '正在进行'
      },
      transformState(data) {
        const currentTime = new Date().getTime() / 1000
        const starttime = data.starttime
        const endtime = data.endtime
        let status
        if (currentTime < starttime) {
          status = 1
        } else if (currentTime > endtime) {
          status = 3
        } else {
          status = 2
        }
        switch (status) {
          case 1:
            data.status = '未进行'
            break
          case 2:
            data.status = '进行中'
            break
          case 3:
            data.status = '已结束'
            break
          default:
            break
        }
      }
    },
  }
</script>

<style lang="scss">
  .app-container {
    width: 100%;
    height: 100%;
    background: url('../../assets/bg1.jpg') no-repeat;
    background-size: 100% 100%;

    .ivu-menu-horizontal.ivu-menu-light:after {
      background: none;
    }

    .ivu-tabs {
      height: 100%;
      .ivu-tabs-bar {
        border-color: #95a0ad;
      }
      .ivu-tabs-nav {
        width: 100%;
        /* Tabs字体大小 */
        font-size: 2.2rem;
        font-weight: bold;
        font-family: "SimHei";

        .ivu-tabs-ink-bar {
          height: 5px;
          width: 40% !important;
          margin-left: 5%;
          margin-right: 5%;
        }

        .ivu-tabs-tab {
          width: 50%;
          color: #000;
        }
      }

      .ivu-tabs-content-animated {
        height: 90%;

        .ivu-tabs-tabpane {
          height: 100%;

          .left {
            width: 60%;
            height: 100%;
            float: left;
            display: flex;
            flex-direction: column;
            justify-content: space-around;

            .theme {
              color: #000;
              font-size: 2.5rem;
            }
            .time {
              color: #000;
              font-size: 2.8rem;
            }
          }

          .left2 {
            margin-left: 1rem;
            width: 65%;
            height: 100%;
            float: left;
            display: flex;
            flex-direction: column;
          }

          .right2 {
            width: 32%;
            height: 100%;
            float: right;
            display: flex;
            flex-direction: column;
            justify-content: center;
          }
          
          .right {
            width: 40%;
            height: 100%;
            float: right;
            .btnContainer {
              .btnCol {
                button {
                  color: #fff;
                  background-color: #3F68CC;
                  border-color: #3F68CC;
                  font-size: 1.2rem;
                }
                #snap {
                  margin-top: 1rem;
                }
              }
            }
            .videoContainer {
              .videoCol {
                #canvas {
                  width: 300px;
                  height: 300px;
                }
                #canvas1 {
                  width: 300px;
                  height: 300px;
                  border: 1px solid gray;
                }
                #video {
                  // width: 80%;
                  // height: 60%;
                  opacity: 0;
                  position: absolute;
                  // display: none;
                  width: 300px;
                  height: 300px;
                }
              }
            }
          }
        }
      }
    }
    h1 {
      color: #000;
    }
  }

  .ivu-modal {
    .ivu-modal-body {
      display: flex;
      justify-content: center;
    }
  }
</style>

<style>
  .meeting-card {
    /* background-image: url('../../assets/bg2.png');
    background-repeat: no-repeat;
    background-position: center -125px;
    background-size: 100% 125%;
    background-origin: border-box; */
    position: absolute;
    top: 52%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    width: 100%;
    height: 90%;
    /* TabPane字体大小 */
    font-size: 1.3rem;
    font-family: "SimHei";
  }

  .meeting-status {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    width: 100%;
    height: 85%;
  }

  .ivu-tabs {
    border: 10px solid #9faac4;
    background-color: rgba(222, 237, 250, .85);
  }

  /*表头*/
  .ivu-table th {
    background-color: #3770b7;
    color: #fff;
  }

  /*偶数行*/
  .ivu-table-stripe-even td {
    background-color: #f3bf5d;
  }

  /*奇数行*/
  .ivu-table-stripe-odd td {
    background-color: #85acdf;
  }

  /*浮在某行*/
  table tr.ivu-table-row-hover td {
    background-color: rgb(169, 170, 169);
  }

  .table {
    border: 3px solid #aab4cc;
    height: 100%
  }

  .ivu-table-border td {
    border-right: 2px solid #e8eaec;
  }

  /*表格字体*/
  .ivu-table-large {
    font-size: 1.5rem;
    font-weight: bold;
    color: black;
  }
</style>